package com.cms.fom.service.impl;

import com.alibaba.fastjson.TypeReference;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.cms.common.exception.RRException;
import com.cms.common.utils.R;
import com.cms.fom.dao.TaskDao;
import com.cms.fom.entity.TaskEntity;
import com.cms.fom.entity.vo.MonitorListVo;
import com.cms.fom.entity.vo.MonitorVo;
import com.cms.fom.entity.vo.StuProcessVo;
import com.cms.fom.feign.StuFeign;
import com.cms.fom.feign.ThirdPartyFeign;
import com.cms.fom.to.StudentTo;
import net.bytebuddy.implementation.bytecode.Throw;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.util.*;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.cms.common.utils.PageUtils;
import com.cms.common.utils.Query;

import com.cms.fom.dao.MonitorDao;
import com.cms.fom.entity.MonitorEntity;
import com.cms.fom.service.MonitorService;

import javax.annotation.Resource;


@Service("monitorService")
public class MonitorServiceImpl extends ServiceImpl<MonitorDao, MonitorEntity> implements MonitorService {

    @Resource
    private TaskDao taskDao;

    @Resource
    private ThirdPartyFeign thirdPartyFeign;

    @Resource
    private StuFeign stuFeign;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<MonitorEntity> page = this.page(
                new Query<MonitorEntity>().getPage(params),
                new QueryWrapper<MonitorEntity>()
        );

        List<MonitorListVo> result = page.getRecords().stream().map(item -> {
            MonitorListVo monitorListVo = new MonitorListVo();
            Long studentId = item.getStudentId();
            R r = stuFeign.info(studentId);
            StudentTo student = r.getData("student", new TypeReference<StudentTo>() {
            });
            BeanUtils.copyProperties(item, monitorListVo);
            monitorListVo.setStudentName(student.getName());
            return monitorListVo;
        }).collect(Collectors.toList());

        IPage<MonitorListVo> resultPage = new Page<>();
        resultPage.setTotal(page.getTotal());
        resultPage.setSize(page.getSize());
        resultPage.setPages(page.getPages());
        resultPage.setCurrent(page.getCurrent());
        resultPage.setRecords(result);

        return new PageUtils(resultPage);
    }

    @Override
    public MonitorVo detailInfo(Long id) {
        MonitorVo monitorVo = new MonitorVo();


        List<TaskEntity> taskEntities = taskDao.selectList(new QueryWrapper<TaskEntity>().orderByDesc("update_time"));
        TaskEntity taskEntity = taskEntities.get(0);
        if(taskEntity.getIsShow() == 1){
            MonitorEntity monitorEntity = baseMapper.selectOne(new QueryWrapper<MonitorEntity>().eq("student_id", id).eq("task_id", taskEntity.getId()));

            if(monitorEntity != null){
                monitorVo.setId(monitorEntity.getId());
                String[] times = monitorEntity.getTime().split(",");
                String img = monitorEntity.getImg();
                String[] imgs = null;
                List<MonitorVo.MonitorData> voMonitorData = new ArrayList<>();
                if(!StringUtils.isEmpty(img)){
                    imgs = img.split(",");
                }
                try{
                    for (int i = 0; i < times.length; i++) {
                        MonitorVo.MonitorData monitorData = new MonitorVo().new MonitorData();
                        monitorData.setTimestamp(times[i]);

                        LocalDate localDate = LocalDate.now();
                        DateFormat format = new SimpleDateFormat("yyyy-MM-dd");
                        Date date = format.parse(times[i]);
                        Calendar calendar = Calendar.getInstance();
                        calendar.setTime(date);
                        int year = calendar.get(Calendar.YEAR);
                        int month = calendar.get(Calendar.MONTH) + 1;
                        int dateDate = calendar.get(Calendar.DATE);
                        LocalDate currentDate = LocalDate.of(year, month, dateDate);

                        if(imgs != null && imgs.length > i){
                            if(!StringUtils.isEmpty(imgs[i])){
                                monitorData.setColor("#0bbd87");
                                monitorData.setContent("已提交");
                                if(currentDate.isEqual(localDate)){
                                    monitorVo.setCurrentUrl(imgs[i]);
                                }
                            }else{
                                monitorVo.setIsError(true);
                                monitorData.setColor("#FF0000");
                                monitorData.setContent("未提交");
                            }
                        }else{
                            monitorVo.setIsError(true);
                            if(currentDate.isBefore(localDate)){
                                monitorData.setColor("#FF0000");
                                monitorData.setContent("未提交");
                                monitorVo.setIsError(true);
                            }else{
                                monitorData.setColor("#F0F0F0");
                                monitorData.setContent("待提交");
                            }
                        }
                        monitorData.setSize("large");
                        voMonitorData.add(monitorData);

                    }
                }catch (Exception e){
                    System.out.println(e.getMessage());
                }

                monitorVo.setMonitorData(voMonitorData);
            }
        }else{
            monitorVo.setIsError(false);
        }





        return monitorVo;
    }

    @Override
    public Boolean uploadImg(Long id, String url) {

        R r = thirdPartyFeign.isPassForImg(url);
        if(r.getCode() == 0){
            Boolean isPass = r.getData("pass", new TypeReference<Boolean>() {
            });
            if(isPass){
                //健康码通过后进行更新操作
                MonitorEntity monitorEntity = baseMapper.selectById(id);
                String[] times = monitorEntity.getTime().split(",");
                String[] imgs = {};
                if(monitorEntity.getImg() != null){
                    imgs = monitorEntity.getImg().split(",");
                }
                StringBuffer stringBuffer = null;
                try{
                    for (int i = 0; i < times.length; i++) {
                        LocalDate date = LocalDate.now();
                        DateFormat format = new SimpleDateFormat("yyyy-MM-dd");
                        Calendar calendar = Calendar.getInstance();
                        calendar.setTime(format.parse(times[i]));
                        LocalDate currentDate = LocalDate.of(calendar.get(Calendar.YEAR), calendar.get(Calendar.MONTH) + 1, calendar.get(Calendar.DATE));
                        if(date.isEqual(currentDate)){
                            stringBuffer = new StringBuffer();
                            for(int j = 0; j < i; j++){
                                if(imgs != null && imgs.length > j){
                                    stringBuffer.append(imgs[j] + ",");
                                }else{
                                    stringBuffer.append(",");
                                }
                            }
                            stringBuffer.append(url);
                            break;
                        }
                    }
                    monitorEntity.setImg(stringBuffer.toString());
                    baseMapper.updateById(monitorEntity);
                }catch (Exception e){
                    System.out.println(e.getMessage());
                    throw new RRException("图片处理失败，请稍后再试！", 1);
                }
                return true;
            }else{
                throw new RRException("您的健康码有异常，请立即联系班主任进行报备！", 1);
            }
        }
        return false;
    }

}